from django import forms
from django.forms import fields, widgets

import re

from .models import Lilun_unit_name

class Lilun_unit_nameForm(forms.Form):
    linlun_unit_name = Lilun_unit_name.objects.values('id','name')
    linlun_unit_header = (0, '------------------------请  选  择------------------------')     # 设置初始题目选择为 ‘---请选择---’

    name = fields.ChoiceField(
        choices=[(linlun_unit_header),] + list(Lilun_unit_name.objects.values_list('id','name').order_by('name')),  # 加入了排序
        widget=widgets.Select(attrs={'class':'select_title form-control input-sm'})
    )

    # 实时跟新网页数据
    def __init__(self,*args, request=None, **kwargs):
        super(Lilun_unit_nameForm, self).__init__(*args, **kwargs)
        linlun_unit_header = (0, '------------------------请  选  择------------------------')     # 设置初始题目选择为 ‘---请选择---’
        if request:     # 适时可以删除else后程序
            courseid = request.session.get('courseid', 1)  # 默认课程id为1
            self.fields['name'].choices = sort_liluntitle_names(linlun_unit_header, list(Lilun_unit_name.objects.filter(course_id=courseid).values_list('id','name').order_by('name')))   # 更新 ， 加入了排序
            # self.fields['name'].choices = [(linlun_unit_header),] + list(Lilun_unit_name.objects.filter(course_id=courseid).values_list('id','name').order_by('name'))    # 更新 ， 加入了排序
            # self.fields['name'].choices = [(linlun_unit_header),] + list(Lilun_unit_name.objects.values_list('id','name').order_by('name'))    # 更新 ， 加入了排序
        else:
            courseid = request.session.get('courseid', 1)  # 默认课程id为1
            # self.fields['name'].choices = [(linlun_unit_header),] + list(Lilun_unit_name.objects.values_list('id','name').order_by('name'))    # 更新 ， 加入了排序
            self.fields['name'].choices = sort_liluntitle_names(linlun_unit_header, list(Lilun_unit_name.objects.filter(course_id=courseid).values_list('id','name').order_by('name')))    # 更新 ， 加入了排序



#  排序后的理论题目
def sort_liluntitle_names(linlun_unit_header, titles):
    '''
    规定：理论题目名称必须是这样的格式：日考'专业+理论+序号.html',周考和月考分别有周考和月考名
    ***** 不是很严谨，后期修改  # 后期修改100 ****
    :param linlun_unit_header:
    :param titles:
    :return:
    '''
    print('===========', titles)
    titles = [(title[1], title) for title in titles]
    titles1 = []    # 存放周月考
    titles2 = []    # 存放日考
    for titlename, title in titles:
        if titlename.find('周考') != -1 or titlename.find('月考') != -1:
            titles1.append(title)
        else:
            titles2.append(title)
    print(titles2)
    titles2.sort(key=lambda x:int(re.findall(r'\d+', x[1])[-1]))
    titles2.insert(0, linlun_unit_header)
    return titles2 + titles1

